#ifndef LIST_H
#define LIST_H

#include <cm/cm_constant.h>

# define POISON_POINTER_DELTA 0

#define LIST_POISON1  ((void *) 0x00100100 + POISON_POINTER_DELTA)
#define LIST_POISON2  ((void *) 0x00200200 + POISON_POINTER_DELTA)

struct list_head {
	struct list_head *prev;
	struct list_head *next;
};

#define LIST_HEAD_INIT(name) {&(name), &(name)}
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)

static inline void init_list_head(struct list_head *list)
{
	list->prev = list;
	list->next = list;
}

/*
 * @brief	将节点node添加到prev和next之间
 */
static inline void __list_add(struct list_head *node, struct list_head *prev,
		struct list_head *next)
{
	prev->next = node;
	node->prev = prev;
	node->next = next;
	next->prev = node;
}

/*
 * @brief	将节点node添加到head的后面
 */
static inline void list_add(struct list_head *node, struct list_head *head)
{
	__list_add(node, head, head->next);
}

/*
 * @brief	将节点node添加到head的前面
 */
static inline void list_add_tail(struct list_head *node, struct list_head *head)
{
	__list_add(node, head->prev, head);
}

/*
 * @brief	删除节点prev和next之间的所有节点，注意：并不释放与之关联的数据
 */
static inline void __list_del(struct list_head *prev, struct list_head *next)
{
	prev->next = next;
	next->prev = prev;
}

/*
 * @brief	将节点entry从链表中删除
 */
static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = LIST_POISON1;
	entry->prev = LIST_POISON2;
}

/*
 * @brief	将节点list移动到head的后面
 */
static inline void list_move(struct list_head *list, struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add(list, head);
}

/*
 * @brief	将节点list移动到head的前面(或者说链表的尾部)
 */
static inline void list_move_tail(struct list_head *list,
		struct list_head *head)
{
	__list_del(list->prev, list->next);
	list_add_tail(list, head);
}

#define list_entry(ptr, type, member) \
	container_of(ptr, type, member)

#define list_first_entry(ptr, type, member) \
	list_entry((ptr)->next, type, member)

#define list_for_each(pos, head) \
	for (pos = (head)->next; pos != (head); pos = pos->next)

#define list_for_each_safe(pos, n, head) \
	for (pos = (head)->next, n = pos->next; pos != (head);\
	pos = n, n = pos->next)

#define list_empty(head) ((head)->prev == (head)->next)

#endif

